//
//  YDLoginController.m
//  PeiZiWangBei
//
//  Created by LK-IOS on 2017/11/13.
//  Copyright © 2017年 LK-IOS. All rights reserved.
//

#import "YDLoginController.h"

#import "YDFindBackPasswordViewController.h"
#import "YDRegisterController.h"


@interface YDLoginController ()<UITextFieldDelegate>

//电话图标
@property (nonatomic , weak) UIImageView *phoneImage;
//号码输入框
@property (nonatomic , weak) SYPhoneTextField *phoneTextField;
//号码下划线
@property (nonatomic , weak) UIView *phoneLineView;
//密码图标
@property (nonatomic , weak) UIImageView *passImage;
//密码输入框
@property (nonatomic , weak) UITextField *passTextField;
//密码下划线
@property (nonatomic , weak) UIView *passLineView;
//密码可见按钮
@property (nonatomic , weak) SYNoHeightedButton *passButton;
//忘记密码
@property (nonatomic , weak) UILabel *passPostLabel;
//确认按钮
@property (nonatomic , weak) SYNoHeightedButton *sureButton;
//用户输入的手机号和密码
@property (nonatomic , copy) NSString *userPhoneNumber;
@property (nonatomic , copy) NSString *userPassCode;

@end

@implementation YDLoginController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"登录";
    [self setUpNavButton];
    //给界面添加点击手势，点击退出编辑
    [self dismissKeyBoard];
    [self addChildViews];
    //给输入框添加监听，控制登录按钮是否可以点击
    [self.phoneTextField addTarget:self action:@selector(textchange) forControlEvents:UIControlEventAllEditingEvents];
    [self.passTextField addTarget:self action:@selector(textchange) forControlEvents:UIControlEventAllEditingEvents];

}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.phoneTextField.text = [[SYUserDataManger sharedInstance] getUerPhone].length ? [NSString phoneNumberFormate:[[SYUserDataManger sharedInstance] getUerPhone]] : @"";
}
-(void)setUpNavButton
{
    //zhmm
    
    if (self.loginStyle == Login_Present) {
        //present进来的左上角按钮为关闭
        UIBarButtonItem *leftItemBtn = [UIBarButtonItem imageWithNormalImage:[UIImage imageNamed:@"rightClose"] hightImage:[UIImage imageNamed:@"rightClose"] addTarget:self action:@selector(leftItemButtonClick:)];
        self.navigationItem.leftBarButtonItem = leftItemBtn;
        
    }
    UIBarButtonItem *rightItemBtn = [UIBarButtonItem imageWithNormalImage:[UIImage imageNamed:@"regisier copy"] hightImage:[UIImage imageNamed:@"regisier copy"] addTarget:self action:@selector(rightItemButtonClick:)];
    self.navigationItem.rightBarButtonItem = rightItemBtn;
}
-(void)rightItemButtonClick:(UIButton *)button
{
    YDRegisterController *vc = [[YDRegisterController alloc] init];
    vc.hidesBottomBarWhenPushed = YES;
    vc.loginStyle = self.loginStyle;
    [self.navigationController pushViewController:vc animated:YES];
    
  
}

- (void)leftItemButtonClick:(UIButton *)sender
{
    LKKeyValueStore *store = [LKKeyValueStore sharedInstanceWithdbName:peizidbName];
    
    if ([store isExistTableWithName:peiziuserDataName]) {//存在个人信息表
        [store deleteTable:peiziuserDataName];
    }else{//不存在
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)textchange
{

    //手机号清空 密码自动清空
    if ([self.phoneTextField.text isEqualToString:@""]) {
        self.passTextField.text = @"";
    }
    self.sureButton.enabled = self.phoneTextField.text.length && self.passTextField.text.length;
}

///添加子控件
-(void)addChildViews
{
    [self phoneLineView];
    [self phoneImage];
    [self phoneTextField];
    [self passLineView];
    [self passImage];
    [self passButton];
    [self passTextField];
    [self passPostLabel];
    [self sureButton];

}



-(void)sureButtonClick:(SYNoHeightedButton *)button
{
    [self.view endEditing:YES];
    //保留用户输入信息
    self.userPhoneNumber = [self.phoneTextField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    self.userPassCode = self.passTextField.text;
    
    //判断是不是复合标准
 
    if (![NSString isPhoneNumber:self.userPhoneNumber]) {
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view
                                                        WithType:NavTipsViewTypeMessage
                                                            text:@"请输入正确的手机号"
                                                      isExistNav:YES];
        return;
    }
    
        
        [self sendUserLoginInformation];
    
    
}
-(void)forgetPasswordBtnDidSelected
{
  
    YDFindBackPasswordViewController *vc = [[YDFindBackPasswordViewController alloc] init];
  
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}
/**
 用户退出登录或者token 过期的话，清空数据库中用户信息，所以再次登录的时候，重新保存用户信息
 ***/
-(void)sendUserLoginInformation
{
    [[SYProgressHUD sharedInstance] showMBHudWithSting:kLoadingText];
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    
    [dict setObject:self.userPhoneNumber forKey:@"phone"];
    [dict setObject:self.userPassCode forKey:@"password"];
    
    [BaseNetRequest sessionRequestWithparameters:dict method:POSTMethod requstType:Login WithSuccessBlock:^(NSDictionary *resultDict) {
        
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        
        if ([resultDict[@"code"] integerValue] == 200) {//登录成功
            [self resloveUserInformationWithDict:resultDict[@"result"]];//处理一下用户信息
            [self uploadJpushId];
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeSuccess text:@"登录成功" isExistNav:YES];
        }else if ([resultDict[@"code"] integerValue] == 2003){//用户名或密码错误
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"用户名或密码错误" isExistNav:YES];
        }else{
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:resultDict[@"message"] isExistNav:YES];
        }
    } failBlock:^(NSError *error) {
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        if ([ErrorMessageManager showErrorMessageWithError:error vc:self]) {
            
        }else
        {
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"服务器忙，请稍后重试" isExistNav:YES];
        }
        
    }];
    
 
}


/**
 上传极光id
 */
-(void)uploadJpushId
{
//    NSMutableDictionary *prams = [NSMutableDictionary new];
//    [prams setValue:[SYUserInformation sharedInstance].registrationID forKey:@"registrationId"];
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{

        [[SYVersionManger sharedInstance] upLoadJpushID];
    });
}
-(void)resloveUserInformationWithDict:(NSDictionary *)dict
{
    [[SYUserDataManger sharedInstance] storeUserDataWithDict:dict];
    
    [[SYUserDataManger sharedInstance] storeUserToken:dict[@"token"]];
    
    //
    [SYUserInformation sharedInstance].isLogin = YES;

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (self.loginStyle == Login_Push) {
            [self.navigationController popViewControllerAnimated:YES];
        }
        else if (self.loginStyle == Login_Present)
        {
            [self dismissViewControllerAnimated:YES completion:nil];
        }
    });

    
}

#pragma UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;
{
    
    if ([textField isFirstResponder]) {
        if ([[[textField textInputMode] primaryLanguage] isEqualToString:@"emoji"] || ![[textField textInputMode] primaryLanguage]) {
            return NO;
        }
    }
    if (textField == _phoneTextField) {
        //字符个数限制
        NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
        if ([toBeString length] > 13) {
            
            return NO;
        }
        //忽略空格
        if([string hasSuffix:@" "]){
            // 忽视空格
            return NO;
        }else{
            return YES;
        }
        
    }else{
        //密码输入框处理
        //字符个数限制
        NSString * passString = [textField.text stringByReplacingCharactersInRange:range withString:string];
        if ([passString length] > 12) {
            
            return NO;
        }
        //忽略小数点和空格
        if([string isEqualToString:@"."] || [string hasSuffix:@" "]){
            // 忽视空格
            return NO;
        }else{
            return YES;
        }
        
    }

    return YES;
}


//////**********添加控件部分********//////
///**********号码下划线********///
-(UIView *)phoneLineView
{
    if (_phoneLineView == nil) {
        UIView *phoneLineView = [[UIView alloc] init];
        [self.view addSubview:phoneLineView];
        //236 231 231
        phoneLineView.backgroundColor = NumberColor(236, 231, 231);
        [phoneLineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view).offset(rate375(20));
            make.right.equalTo(self.view).offset(-rate375(20));
            make.centerX.equalTo(self.view);
            make.height.equalTo(@1);
            if (isPhoneX) {
                make.top.equalTo(self.view).offset(rateX812(80));
            }else{
                make.top.equalTo(self.view).offset(rate750(60));
            }
        }];
        
        _phoneLineView = phoneLineView;
    }
    return _phoneLineView;
}
///*********电话图标*********///
-(UIImageView *)phoneImage
{
    if (_phoneImage == nil) {
        UIImageView *phoneImage = [[UIImageView alloc] init];
        [self.view addSubview:phoneImage];
        phoneImage.backgroundColor = [UIColor clearColor];
        phoneImage.image = [UIImage imageNamed:@"dl-shouji"];
        phoneImage.contentMode = UIViewContentModeScaleToFill;
        [phoneImage mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view).offset(rate375(25));
            make.width.equalTo(@(rate375(12)));
            if (isPhoneX) {
                make.height.equalTo(@(rateX812(16)));
                make.bottom.equalTo(self.phoneLineView.mas_top).offset(-rateX812(10));
            }else{
                make.height.equalTo(@(rate750(16)));
                make.bottom.equalTo(self.phoneLineView.mas_top).offset(-rate750(10));
            }
        }];
        _phoneImage = phoneImage;
    }
    return _phoneImage;
}
///********号码输入框**********///
-(SYPhoneTextField *)phoneTextField
{
    if (_phoneTextField == nil) {
        SYPhoneTextField *phoneTextField = [[SYPhoneTextField alloc] init];
        [self.view addSubview:phoneTextField];
        phoneTextField.textColor = [UIColor blackColor];
        phoneTextField.font = [UIFont systemFontOfSize:font14ScreenWRate * LKScreenW];
        phoneTextField.placeholder = @"请输入手机号码";
        
        phoneTextField.backgroundColor = [UIColor clearColor];
        phoneTextField.borderStyle = UITextBorderStyleNone;
        phoneTextField.textAlignment = NSTextAlignmentLeft;
        phoneTextField.keyboardType = UIKeyboardTypeNumberPad;
        phoneTextField.autocapitalizationType = UITextAutocapitalizationTypeNone;
        phoneTextField.keyboardAppearance=UIKeyboardAppearanceDefault;
        phoneTextField.returnKeyType =UIReturnKeyDone;
        [phoneTextField setClearButtonMode:UITextFieldViewModeWhileEditing];
        [phoneTextField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.phoneImage);
            make.left.equalTo(self.phoneImage.mas_right).offset(rate375(13));
            make.right.equalTo(self.phoneLineView);
            if (isPhoneX) {
                make.height.equalTo(@(rateX812(20)));
            }else{
                make.height.equalTo(@(rate750(20)));
            }
        }];
        phoneTextField.tintColor = [UIColor blackColor];
        phoneTextField.delegate = self;
        
        
        _phoneTextField = phoneTextField;
    }
    return _phoneTextField;
}

///**********密码下划线********///
-(UIView *)passLineView
{
    if (_passLineView == nil) {
        UIView *passLineView = [[UIView alloc] init];
        [self.view addSubview:passLineView];
        passLineView.backgroundColor = NumberColor(236, 231, 231);
        [passLineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view).offset(rate375(20));
            make.right.equalTo(self.view).offset(-rate375(20));
            make.centerX.equalTo(self.view);
            make.height.equalTo(@1);
            if (isPhoneX) {
                make.top.equalTo(self.phoneLineView.mas_bottom).offset(rateX812(52));
            }else{
                make.top.equalTo(self.phoneLineView.mas_bottom).offset(rate750(52));
            }
        }];
        
        _passLineView = passLineView;
    }
    return _passLineView;
}
///*********密码图标*********///
-(UIImageView *)passImage
{
    if (_passImage == nil) {
        UIImageView *passImage = [[UIImageView alloc] init];
        [self.view addSubview:passImage];
        passImage.backgroundColor = [UIColor clearColor];
        passImage.image = [UIImage imageNamed:@"dl-mima"];
        passImage.contentMode = UIViewContentModeScaleToFill;
        [passImage mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view).offset(rate375(25));
            make.width.equalTo(@(rate375(12)));
            if (isPhoneX) {
                make.height.equalTo(@(rateX812(16)));
                make.bottom.equalTo(self.passLineView.mas_top).offset(-rateX812(10));
            }else{
                make.height.equalTo(@(rate750(16)));
                make.bottom.equalTo(self.passLineView.mas_top).offset(-rate750(10));
            }
        }];
        _passImage = passImage;
    }
    return _passImage;
}
///*********密码可见按钮*********///
-(SYNoHeightedButton *)passButton
{
    if (_passButton == nil) {
        SYNoHeightedButton *passButton = [SYNoHeightedButton buttonWithType:UIButtonTypeCustom];
        [self.view addSubview:passButton];
        passButton.backgroundColor = [UIColor clearColor];
        [passButton setImage:[UIImage imageNamed:@"dl-yincang"] forState:UIControlStateNormal];
        [passButton setImage:[UIImage imageNamed:@"dl-xianshi"] forState:UIControlStateSelected];
        [passButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self.view).offset(-rate375(25));
            make.centerY.equalTo(self.passImage);
            make.width.equalTo(@(rate375(50)));
            if (isPhoneX) {
                make.height.equalTo(@(rateX812(30)));
            }else{
                make.height.equalTo(@(rate750(30)));
            }
        }];
        [passButton addTarget:self action:@selector(passButtonClick:) forControlEvents:UIControlEventTouchDown];
        _passButton = passButton;
    }
    return _passButton;
}
-(void)passButtonClick:(SYNoHeightedButton *)button
{
    self.passButton.selected = !self.passButton.selected;
    if (self.passButton.selected) {
        self.passTextField.secureTextEntry = NO;
       
    }else{
        self.passTextField.secureTextEntry = YES;
    }
    
}
///*********密码输入框*********///
-(UITextField *)passTextField
{
    if (_passTextField == nil) {
        UITextField *passTextField = [[UITextField alloc] init];
        [self.view addSubview:passTextField];
        passTextField.textColor = [UIColor blackColor];
        passTextField.font = [UIFont systemFontOfSize:font14ScreenWRate * LKScreenW];
        passTextField.placeholder = @"请输入密码";
        passTextField.backgroundColor = [UIColor clearColor];
        passTextField.borderStyle = UITextBorderStyleNone;
        passTextField.textAlignment = NSTextAlignmentLeft;
        passTextField.keyboardType = UIKeyboardTypeDefault;
        passTextField.autocapitalizationType = UITextAutocapitalizationTypeNone;
        passTextField.keyboardAppearance=UIKeyboardAppearanceDefault;
        passTextField.returnKeyType =UIReturnKeyDone;
        [passTextField setClearButtonMode:UITextFieldViewModeWhileEditing];
        passTextField.secureTextEntry = YES;
        [passTextField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.passImage);
            make.left.equalTo(self.passImage.mas_right).offset(rate375(13));
            make.right.equalTo(self.view).offset(-rate375(60));
            if (isPhoneX) {
                make.height.equalTo(@(rateX812(20)));
            }else{
                make.height.equalTo(@(rate750(20)));
            }
        }];
        passTextField.delegate = self;
        passTextField.tintColor = [UIColor blackColor];
        
        _passTextField = passTextField;
    }
    return _passTextField;
}
//密码输入提示文字
-(UILabel *)passPostLabel
{
    if (_passPostLabel == nil) {
        UILabel *passPostLabel = [[UILabel alloc] init];
        [self.view addSubview:passPostLabel];
        passPostLabel.textColor = NumberColor(62, 89, 167);
        NSMutableAttributedString *attribtStr = [[NSMutableAttributedString alloc]initWithString:@"忘记密码？" attributes:@{NSUnderlineStyleAttributeName:@(NSUnderlineStyleSingle)}];
        
        passPostLabel.attributedText = attribtStr;
        passPostLabel.font = [UIFont systemFontOfSize:font12ScreenWRate * LKScreenW];
        passPostLabel.textAlignment = NSTextAlignmentRight;
        [passPostLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self.view).offset(rate375(-20));
            if (isPhoneX) {
                make.top.equalTo(self.passLineView.mas_bottom).offset(rateX812(12));
            }else{
                make.top.equalTo(self.passLineView.mas_bottom).offset(rate750(12));
            }
        }];
        passPostLabel.userInteractionEnabled = YES;
        [passPostLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(forgetPasswordBtnDidSelected)]];
         
        _passPostLabel = passPostLabel;
      
        
        
    }
    return _passPostLabel;
}

-(SYNoHeightedButton *)sureButton
{
    if (_sureButton == nil) {
        SYNoHeightedButton *sureButton = [SYNoHeightedButton buttonWithType:UIButtonTypeCustom];
        [self.view addSubview:sureButton];
        [sureButton setBackgroundImage:[UIImage imageWithColor:[UIColor colorWithHexString:Orange alpha:0.3]] forState:UIControlStateDisabled];
        [sureButton setBackgroundImage:[UIImage imageWithColor:[UIColor colorWithHexString:Orange]] forState:UIControlStateNormal];
        [sureButton setTitle:@"确认" forState:UIControlStateNormal];
        [sureButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [sureButton setTitleColor:[UIColor whiteColor] forState:UIControlStateDisabled];
        sureButton.titleLabel.font = [UIFont systemFontOfSize:font16ScreenWRate * LKScreenW];
        sureButton.titleLabel.textAlignment = NSTextAlignmentCenter;
        
        [sureButton mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.width.equalTo(@(rate375(284)));
            make.centerX.equalTo(self.view);
            if (isPhoneX) {
                make.height.equalTo(@(rateX812(48)));
                make.top.equalTo(self.passPostLabel.mas_bottom).offset(rateX812(38));
            }else{
                make.height.equalTo(@(rate750(48)));
                make.top.equalTo(self.passPostLabel.mas_bottom).offset(rate750(38));
            }
            
        }];
        sureButton.enabled = NO;
        [sureButton addTarget:self action:@selector(sureButtonClick:) forControlEvents:UIControlEventTouchDown];
        sureButton.layer.cornerRadius = 5.0f;
        sureButton.layer.masksToBounds = YES;
        
        _sureButton = sureButton;
    }
    return _sureButton;
}



@end
